//
//  WebViewController.m
//  CommonFrame
//
//  Created by Bang-guo on 15/7/18.
//  Copyright (c) 2015年 guobang. All rights reserved.
//

#import "WebViewController.h"

@interface WebViewController ()

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
//    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 20 - 44 - 49)];
//    webView.scalesPageToFit = YES; //自动适应屏幕
//    //    "http://www.gx.xinhuanet.com/2015-06/12/c_1115558892.htm"
//    NSURL *url = [NSURL URLWithString:self.recommendScroll.url];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [webView loadRequest:request];
//    [self.view addSubview:webView];
//    webView.delegate = self;
    
    self.webTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 20 - 44 - 49) style:UITableViewStylePlain];
    self.webTableView.delegate = self;
    self.webTableView.dataSource = self;
    [self.view addSubview:self.webTableView];
    
    
    
    self.imageArray = [NSMutableArray array];
    self.contentArray = [NSMutableArray array];
    [self getDataValue];
    //让菊花旋转起来
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载中...";
    [self.HUD show:YES];

    
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"cell";
    WebTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        
        cell = [[WebTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    if (self.imageArray.count != 0 && self.contentArray.count != 0 ) {
        
        cell.imageStr = self.imageArray[indexPath.row];
        cell.contentStr = self.contentArray[indexPath.row];
        
    }
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.contentArray.count != 0 ) {
        CGFloat fl =  [self heightCustom:self.contentArray[indexPath.row]];
        return 200 + fl + 10;
    }
    
    return 0;
    
}
-(CGFloat)heightCustom:(NSString *)content {
    //参数1.设置计算内容的宽度
    //参数2.设置计算高度
    //参数3.设置字体大小属性
    //参数4.系统备用参数,设置为nil
    
    //其中宽度一定与消失内容的label宽度一致,否则不准确
    CGSize size = CGSizeMake(WIDTH, 100000);
    
    //字体大小一定与显示内容的label字体大小一致,默认 17
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName];
    
    CGRect frame = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    
    return frame.size.height;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.imageArray.count > self.contentArray.count) {
        
        return self.contentArray.count - 1;
        
    } else {
        
        
        return self.imageArray.count - 1;
    }
    
    
}


-(void)getDataValue {
    
    
    // AFN网络请求管理
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 设置返回值类型为http数据即responseObject为NSData类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 请求地址(面包旅行的详情页)
    NSString *str = [NSString stringWithFormat:@"%@", self.recommendScroll.url];
    NSLog(@"%@", str);
    // GET请求
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 将请求的Data类型的HTML, 转成我们需要的对象TFHpple
        self.httpCode = [[TFHpple alloc] initWithHTMLData:responseObject];
        // 在httpCode中寻找所有h2标题(其中//h2对应HTML代码中的节点)
        NSArray *titles = [self.httpCode searchWithXPathQuery:@"//h2"];
        // 遍历标题的数组
        for (TFHppleElement *element in titles) {
            // 如果有内容则打印
            if (element.text) {
//                NSLog(@"标题=%@", element.text);
                self.navigationItem.title = element.text;
            }
        }
        // 在httpCode中寻找所有p标签的正文(其中//p对应HTML代码中的节点)
        NSArray *texts = [self.httpCode searchWithXPathQuery:@"//p"];
        // 遍历正文数组
        for (TFHppleElement *element in texts) {
            // 如果正文不为空则进入
            if (element.text != nil) {
                NSString *str = element.text;
                // 数据处理时, 总有多余的回车出现, 在这里处理了一下
                str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                // 数据中出现12个空格的字符串, 处理掉
                if (str.length != 12) {
                    
                    [self.contentArray addObject:str];
                    
//                    NSLog(@"内容=========\n %@", str);
                }
            }
        }
        // 在httpCode中寻找div中的style中的图片(其中//div对应HTML代码中的节点)
        NSArray *images = [self.httpCode searchWithXPathQuery:@"//img"];
        // 遍历图片数组
        for (TFHppleElement *element in images) {
            // 如果数组中element对象的style不为空(其中style对应div的style属性, 即节点属性)
            NSString *str = [element objectForKey:@"src"];
            if (str != nil) {
                // HTML代码中原数据为background-image: url(http://breadtripimages.qiniudn.com/photo_2014_05_20_ecc5cea81cc7283e271dfa8a30f75184.jpg?imageView/2/w/960/q/85)
                // 因此需要将多余内容处理掉, 才能得到我们想要的图片数据
                //                str = [str stringByReplacingOccurrencesOfString:@"background-image: url(" withString:@""];
                //                str = [str stringByReplacingOccurrencesOfString:@")" withString:@""];
//                NSLog(@"图片=%@", str);
                [self.imageArray addObject:str];
            }
        }
        
        [self.webTableView reloadData];
        [self.HUD hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败");
    }];
    
}



//-(void)webViewDidStartLoad:(UIWebView *)webView {
////    NSLog(@"webViewDidStartLoad");
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 20 - 44 - 49)];
//    [view setTag:108];
//    [view setBackgroundColor:[UIColor blackColor]];
//    [view setAlpha:0.5];
//    [self.view addSubview:view];
//    
//    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
//    [self.activityIndicator setCenter:view.center];
//    [self.activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
//    [view addSubview:self.activityIndicator];
//    
//    [self.activityIndicator startAnimating];
//    
//    
//    
//}
//-(void)webViewDidFinishLoad:(UIWebView *)webView {
////    NSLog(@"webViewDidFinishLoad");
//    [self.activityIndicator stopAnimating];
//    UIView *view = (UIView*)[self.view viewWithTag:108];
//    [view removeFromSuperview];
//}
//-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
////    NSLog(@"didFailLoadWithError%@", error);
//    [self.activityIndicator stopAnimating];
//    UIView *view = (UIView*)[self.view viewWithTag:108];
//    [view removeFromSuperview];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
